package cn.hxsteel.storage.module.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.hxsteel.core.exception.ValidateFailException;
import cn.hxsteel.jpart.pager.PagerVO;
import cn.hxsteel.model.bo.ViewBO;
import cn.hxsteel.purview.core.config.constant.SessionConst;
import cn.hxsteel.purview.core.tool.SessionTool;
import cn.hxsteel.purview.model.vo.SessionVO;
import cn.hxsteel.storage.core.base.BaseController;
import cn.hxsteel.storage.core.config.Config;
import cn.hxsteel.storage.core.config.constant.CommonConst;
import cn.hxsteel.storage.model.po.BranchPO;
import cn.hxsteel.storage.model.po.CompanyPO;
import cn.hxsteel.storage.model.po.CustomerPO;
import cn.hxsteel.storage.model.vo.UserLoginVO;
import cn.hxsteel.storage.module.user.model.BranchBO;
import cn.hxsteel.storage.module.user.model.UserBO;

/**
 * 用户的控制器
 */
@Controller
public class UserController extends BaseController
{
    @Autowired
    private UserService userService;
    
    /**
     * 公司管理的主视图
     */
    @RequestMapping( "/companyManage" )
    public ModelAndView companyManageView( HttpServletRequest request )
    {
	ModelAndView res = new ModelAndView();
	String[] uriArray = new String[] { "/company", "/branch", "/user" };
	String viewName = getUserPermitViewName( uriArray, request );
	res.setViewName( viewName );
	return res;
    }
    
    /**
     * 注册视图
     */
    @RequestMapping( value = "/register" )
    public String register()
    {
	return "/user/register";
    }
    
    /**
     * 验证用户名
     * 
     * @param username 用户名称
     */
    @RequestMapping( value = "/valid/username/do" )
    public @ResponseBody
    boolean validUsername( String username )
    {
	return !userService.existUsername( username );
    }
    
    /**
     * 验证用户名
     * 
     * @param username 用户名称
     * @param ID 用户ID
     */
    @RequestMapping( value = "/valid/usernameAndID/do" )
    public @ResponseBody
    boolean validUsernameAndID( int id, String username )
    {
	return !userService.existUsernameAndID( id, username );
    }
    
    /**
     * 请求注册
     * 
     * @param CustomerPO 用户的持久对象
     */
    @RequestMapping( value = "/register/do" )
    public ModelAndView register( CustomerPO CustomerPO, HttpServletRequest request )
    {
	ModelAndView res = new ModelAndView();
	res.setViewName( getRedirectUrl( "/index" ) );
	try
	{
	    validator.validate( CustomerPO );
	    userService.register( CustomerPO );
	    SessionVO< CustomerPO > sessionVO = userService.getSessionVO( CustomerPO );
	    SessionTool.setSessionVO( sessionVO, request );
	    res.addObject( OK_KEY, CustomerPO );
	}
	catch ( Exception e )
	{
	    res.setViewName( "/user/register" );
	}
	return res;
    }
    
    /**
     * 登录视图
     */
    @RequestMapping( value = "/login" )
    public String login()
    {
	return "/user/login";
    }
    
    /**
     * 请求登陆
     * 
     * @param userLoginVO 用户的登录值对象
     */
    @RequestMapping( "/login/do" )
    public ModelAndView login( UserLoginVO userLoginVO, String code, HttpServletRequest request )
    {
	ModelAndView res = new ModelAndView();
	res.setViewName( "/user/login" );
	try
	{
	    // 检查验证码
	    String codeContext = (String) request.getSession().getAttribute( CommonConst.SESSION_CODE_CONTEXT );
	    boolean isErrorCode = codeContext == null || code == null || !codeContext.toLowerCase().equals( code.toLowerCase() );
	    if ( !Config.DEBUG && isErrorCode )
	    {
		res.addObject( FAIL_KEY, "验证码错误" );
	    }
	    else
	    {
		// 检查数据
		CustomerPO CustomerPO = userService.login( userLoginVO );
		SessionVO< CustomerPO > sessionVO = userService.getSessionVO( CustomerPO );
		SessionTool.setSessionVO( sessionVO, request );
		String toURI = (String) request.getSession().getAttribute( CommonConst.SESSION_LOGIN_TO_URI );
		request.getSession().removeAttribute( CommonConst.SESSION_LOGIN_TO_URI );
		// 如果当前会话中没有保存登录之前的请求URL，则直接跳转到主页
		if ( StringUtils.isEmpty( toURI ) )
		{
		    toURI = "/index";
		}
		toURI = getRedirectUrl( toURI );
		res.setViewName( toURI );
	    }
	}
	catch ( ValidateFailException e )
	{
	    res.addObject( FAIL_KEY, e.getMessage() );
	}
	return res;
    }
    
    /**
     * 注销登录
     * 
     * @param session 会话
     */
    @RequestMapping( "/logout" )
    public String logout( HttpSession session )
    {
	session.removeAttribute( SessionConst.SESSION_VO_CONTEXT );
	return getRedirectUrl( "/index" );
    }
    
    /**
     * 验证公司名称
     * 
     * @param name 公司名称
     */
    @RequestMapping( value = "/valid/company/name/do" )
    public @ResponseBody
    boolean validCompanyname( String name )
    {
	return !userService.existCompanyByName( name );
    }
    
    /**
     * 验证部门名称用于添加操作
     * 
     * @param name 部门名称
     * @param pid 部门PID
     * @param companyid 部门COMPANYID
     * @param request
     * @return
     */
    @RequestMapping( value = "/valid/branch/name/do" )
    public @ResponseBody
    boolean validBranchname( String name, int pid, int companyid, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	return !userService.existBranchBy1( name, uid, pid, companyid );
    }
    
    /**
     * 验证部门名称用于添加操作
     * 
     * @param id 部门ID
     * @param name 部门名称
     * @param pid 部门PID
     * @param companyid 部门COMPANYID
     * @param request
     * @return
     */
    @RequestMapping( value = "/valid/branch/name/do1" )
    public @ResponseBody
    boolean validBranchname1( int id, String name, int pid, int companyid, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	return !userService.existBranchBy2( id, name, uid, pid, companyid );
    }
    
    /**
     * 验证公司名称
     * 
     * @param id 公司ＩＤ
     * @param name 公司名称
     */
    @RequestMapping( value = "/valid/company/nameAndID/do" )
    public @ResponseBody
    boolean validCompanyidAndname( int id, String name )
    {
	return !userService.existCompanyByNameAndID( id, name );
    }
    
    /**
     * 添加公司示图
     * 
     */
    @RequestMapping( value = "/company/add" )
    public String addcompany()
    {
	return "/user/company/add";
    }
    
    /**
     * 请求添加公司
     * 
     * @param companyPO 公司持久化对象
     */
    @RequestMapping( value = "/company/add/do" )
    public ModelAndView addcompany( CompanyPO companyPO )
    {
	
	ModelAndView res = new ModelAndView();
	res.setViewName( getRedirectUrl( "/company" ) );
	try
	{
	    validator.validate( companyPO );
	    userService.addCompany( companyPO );
	    res.addObject( OK_KEY, companyPO );
	}
	catch ( Exception e )
	{
	    res.setViewName( "/user/company/add" );
	}
	return res;
    }
    
    /**
     * 判断显示列表为添加还是查询
     * 
     * @param request 请求
     */
    @RequestMapping( value = "/company" )
    public ModelAndView listcompany( HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	if ( userService.companyList( uid ) == null )
	{
	    mav.setViewName( "user/company/add" );
	}
	else
	{
	    mav.setViewName( "/user/company/search" );
	}
	return mav;
    }
    
    /**
     * 请求查找公司
     * 
     * @param id 公司ID
     */
    @RequestMapping( value = "/company/edit" )
    public ModelAndView companymessage( int id )
    {
	CompanyPO company = userService.companyById( id );
	ModelAndView modelAndView = new ModelAndView( "/user/company/edit" );
	modelAndView.addObject( "company", company );
	return modelAndView;
    }
    
    /**
     * 请求更新公司
     * 
     * @param companyPO 公司对象
     */
    @RequestMapping( value = "/company/edit/do" )
    public ModelAndView updcompany( CompanyPO companyPO )
    {
	ModelAndView res = new ModelAndView();
	res.setViewName( getRedirectUrl( "/company" ) );
	try
	{
	    validator.validate( companyPO );
	    userService.updCompany( companyPO );
	}
	catch ( Exception e )
	{
	    res.setViewName( "/user/company/edit" );
	}
	return res;
    }
    
    /**
     * 显示公司列表
     * 
     * @param request 请求
     */
    @RequestMapping( value = "/branch/add" )
    public ModelAndView listcompanyByUID( HttpServletRequest request, int pid, int companyid )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	mav.setViewName( "/user/branch/add" );
	List< CompanyPO > companylist = userService.companyList( uid );
	List< BranchPO > branchlist = userService.branchBy1( uid, companyid );
	mav.addObject( "branchlist", branchlist );
	mav.addObject( "pid", pid );
	mav.addObject( "companyselect", companyid );
	if ( companylist == null )
	{
	    mav.addObject( "companycount", 0 );
	}
	else
	{
	    mav.addObject( "companycount", 1 );
	}
	mav.addObject( "companyname", userService.companyList( uid ) );
	return mav;
    }
    
    /**
     * 添加部门
     * 
     * @param branchPO 部门对象
     * @param pid 部门PID
     */
    @RequestMapping( value = "/branch/add/do" )
    public ModelAndView addbranch( BranchPO branchpo )
    {
	
	ModelAndView mav = new ModelAndView();
	mav.setViewName( "/user/branch/search" );
	try
	{
	    userService.addBranch( branchpo );
	}
	catch ( Exception e )
	{
	    mav.setViewName( "/user/branch/add" );
	}
	return mav;
    }
    
    /**
     * 列出父部门名称
     * 
     * @param companyid 部门COMPANYID
     * @param request
     * @return
     */
    @RequestMapping( value = "/branch/sel/id" )
    @ResponseBody
    public List< BranchPO > selBranchBy1( int companyid, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	List< BranchPO > branchlist = userService.branchBy1( uid, companyid );
	return branchlist;
    }
    
    /**
     * 列出部门名称
     * 
     * @param companyid 部门COMPANYID
     * @param request
     * @return
     */
    @RequestMapping( value = "/branch/sel1/id" )
    @ResponseBody
    public List< BranchPO > selBranchBy2( int companyid, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	List< BranchPO > branchlist = userService.branchBy2( uid, companyid );
	return branchlist;
    }
    
    /**
     * 通过UID显示公司名称
     * 
     * @param request 请求
     */
    @RequestMapping( value = "/branch" )
    public ModelAndView companyByUID( HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	if ( userService.branchListByUID( uid ) == null )
	{
	    mav.setViewName( getRedirectUrl( "/branch/add?pid=0&companyid=0" ) );
	}
	else
	{
	    mav.setViewName( "/user/branch/search" );
	}
	return mav;
    }
    
    /**
     * 显示部门信息用于修改
     * 
     * @param pid 部门PID
     * @param id 部门ID
     */
    @RequestMapping( value = "/branch/edit" )
    public ModelAndView listbranchBycompanyname( int pid, int id, int companyid )
    {
	ModelAndView mav = new ModelAndView();
	mav.setViewName( "/user/branch/edit" );
	mav.addObject( "companyselected", userService.companyById( companyid ) );
	mav.addObject( "branch", userService.branchByID( id ) );
	return mav;
    }
    
    /**
     * 修改部门信息
     * 
     * @param BranchPO 部门对象
     * @param pid 部门PID
     */
    @RequestMapping( value = "/branch/edit/do" )
    public ModelAndView updbranch( BranchPO branchPO )
    {
	ModelAndView mav = new ModelAndView();
	System.out.println( branchPO.getId() + " " + branchPO.getUid() + " " + branchPO.getCompanyID() + "  " + branchPO.getPid() + " " + branchPO.getName() );
	mav.setViewName( "/user/branch/search" );
	try
	{
	    userService.updBranch( branchPO );
	}
	catch ( Exception e )
	{
	    e.printStackTrace();
	}
	return mav;
    }
    
    /**
     * 分页查询公司操作
     * 
     * @param page 页码
     * @param pageSize 每页显示多少条记录
     * @name 公司名称
     * @param request 请求
     */
    @RequestMapping( value = "/company/s/do" )
    @ResponseBody
    public ViewBO selcompanyPage( int pageNo, int pageSize, String name, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ViewBO pagebo = new ViewBO();
	List< CompanyPO > companylist = userService.CompanyPage( pageNo, pageSize, uid, name );
	PagerVO pagerVO = userService.createPagerData();
	pagebo.putMessage( name );
	pagebo.putData( companylist );
	pagebo.putPager( pagerVO );
	pagebo.put( "name", name );
	return pagebo;
    }
    
    /**
     * 查询部门先取公司列表
     * 
     * @param request 请求
     */
    @RequestMapping( value = "/branch/sel" )
    public ModelAndView selcompanyByUID( HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	mav.setViewName( "/user/branch/search" );
	mav.addObject( "companyname", userService.companyList( uid ) );
	return mav;
    }
    
    /**
     * 分页查询部门
     * 
     * @param pageNo 页码
     * @param PID 部门PID
     * @param name 部门名称
     * @param request 请求
     */
    @RequestMapping( value = "/branch/s/do" )
    @ResponseBody
    public ViewBO selbranchPage( int pageNo, int pageSize, String name, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ViewBO pagerbo = new ViewBO();
	List< BranchBO > branchlist = userService.branchPage( pageNo, pageSize, uid, name );
	PagerVO pagerVO = userService.createPagerData();
	pagerbo.put( "name", name );
	pagerbo.putData( branchlist );
	pagerbo.putPager( pagerVO );
	return pagerbo;
    }
    
    /**
     * 添加用户视图
     */
    @RequestMapping( value = "/user/add" )
    public ModelAndView useradd( HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	mav.addObject( "companylist", userService.companyList( uid ) );
	mav.setViewName( "/user/user/add" );
	return mav;
    }
    
    /**
     * 添加用户
     * 
     * @param CustomerPO 用户对象
     */
    @RequestMapping( value = "/user/add/do" )
    public ModelAndView adduser( CustomerPO CustomerPO )
    {
	ModelAndView res = new ModelAndView();
	res.setViewName( "/user/user/search" );
	try
	{
	    validator.validate( CustomerPO );
	    userService.register( CustomerPO );
	    res.addObject( OK_KEY, CustomerPO );
	}
	catch ( Exception e )
	{
	    res.setViewName( "/user/user/add" );
	}
	return res;
    }
    
    /**
     * 显示视图是添加还是查询
     * 
     * @param request 请求
     */
    @RequestMapping( value = "/user" )
    public ModelAndView userview( HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	if ( userService.userByUID( uid ) == null )
	{
	    mav.setViewName( getRedirectUrl( "/user/add" ) );
	}
	else
	{
	    mav.setViewName( "/user/user/search" );
	}
	return mav;
    }
    
    /**
     * 通过ID和UID取用户信息用于修改
     * 
     * @param id 用户ID
     * @param request 请求
     */
    @RequestMapping( value = "/user/edit" )
    public ModelAndView seluserByID( HttpServletRequest request, int id )
    {
	int uid = getUserSessionVO( request ).getUid();
	ModelAndView mav = new ModelAndView();
	CustomerPO user = userService.userByID( id );
	mav.addObject( "CustomerPO", user );
	mav.addObject( "companylist", userService.companyList( uid ) );
	mav.addObject( "branchlist", userService.branchBy2( uid, user.getCompanyID() ) );
	mav.addObject( "branchselect", user.getBranchID() );
	mav.addObject( "companyselect", user.getCompanyID() );
	mav.setViewName( "/user/user/edit" );
	return mav;
    }
    
    /**
     * 修改用户
     * 
     * @param user 用户对象
     */
    @RequestMapping( value = "/user/edit/do" )
    public ModelAndView upduser( CustomerPO user )
    {
	ModelAndView res = new ModelAndView();
	
	res.setViewName( "/user/user/search" );
	try
	{
	    userService.updUser( user );
	}
	catch ( Exception e )
	{
	    res.setViewName( "/user/user/edit" );
	}
	
	return res;
    }
    
    /**
     * 分页查询用户操作
     * 
     * @param pageNo 页码
     * @param request 请求
     * @param username 用户名
     */
    @RequestMapping( value = "/user/s/do" )
    @ResponseBody
    public ViewBO seluserPage( int pageNo, int pageSize, String username, HttpServletRequest request )
    {
	int uid = getUserSessionVO( request ).getUid();
	ViewBO pagerbo = new ViewBO();
	List< UserBO > userlist = userService.userPage( pageNo, pageSize, uid, username );
	PagerVO pagerVO = userService.createPagerData();
	pagerbo.put( "name", username );
	pagerbo.putData( userlist );
	pagerbo.putPager( pagerVO );
	return pagerbo;
    }
}